import React, { useState, useEffect } from 'react';
import { Card, Button, Progress, message, Modal, Typography, Space, Divider, Statistic, Badge, Tooltip, Row, Col } from 'antd';
import { DownloadOutlined, DatabaseOutlined, ExclamationCircleOutlined, BarChartOutlined, PlayCircleOutlined, WifiOutlined, DisconnectOutlined, LoadingOutlined, SyncOutlined, ReloadOutlined } from '@ant-design/icons';
import { dataAPI } from '../services/api';
import { websocketService } from '../services/websocketService';
import MainLayout from '../components/Layout/MainLayout';

const { Title, Text } = Typography;
const { confirm } = Modal;

interface ProgressState {
  total: number;
  downloaded: number;
  percentage?: number;
  status: 'idle' | 'downloading' | 'completed' | 'error' | 'stopped';
}

interface DetailProgressState extends ProgressState {
  percentage: number;
}

const FundDataDownloader: React.FC = () => {
  const [fundListProgress, setFundListProgress] = useState<ProgressState>({
    total: 0,
    downloaded: 0,
    status: 'idle',
  });

  const [fundDetailProgress, setFundDetailProgress] = useState<DetailProgressState>({
    total: 0,
    downloaded: 0,
    percentage: 0,
    status: 'idle',
  });

  const [fundNavProgress, setFundNavProgress] = useState<DetailProgressState>({
    total: 0,
    downloaded: 0,
    percentage: 0,
    status: 'idle',
  });

  const [fundDetailTaskId, setFundDetailTaskId] = useState<string | null>(null);
  const [fundNavTaskId, setFundNavTaskId] = useState<string | null>(null);
  const [fundListTaskId, setFundListTaskId] = useState<string | null>(null);
  const [currentTaskId, setCurrentTaskId] = useState<number | null>(null);
  const [pollTimeoutId, setPollTimeoutId] = useState<NodeJS.Timeout | null>(null);
  const [navPollTimeoutId, setNavPollTimeoutId] = useState<NodeJS.Timeout | null>(null);
  const [storedFundCount, setStoredFundCount] = useState<number>(0);
  const [totalFundCount, setTotalFundCount] = useState<number>(0);
  const [navStatistics, setNavStatistics] = useState<any>(null);
  const [lastUpdateTime, setLastUpdateTime] = useState<Date | null>(null);
  const [connectionStatus, setConnectionStatus] = useState<'connected' | 'disconnected' | 'connecting'>('disconnected');
  const [isPolling, setIsPolling] = useState<boolean>(false);

  // 检查后端状态的函数
  const checkBackendStatus = async () => {
      try {
        // 检查基金详细信息下载状态
        const progressResponse = await dataAPI.getFundDownloadStatus();
        
        if (progressResponse.success === true) {
          const responseData = progressResponse.data;
          const currentStatus = responseData.current_status;
          const progressInfo = responseData.progress;
          
          // 如果后端正在下载，同步前端状态
          if (currentStatus === 'downloading' || currentStatus === 'DOWNLOADING') {
            if (progressInfo && progressInfo.progress) {
              const progressData = progressInfo.progress;
              const total = progressData.total_count || 0;
              const currentIndex = progressData.current_index || 0;
              const percentage = total > 0 
                ? parseFloat(((currentIndex / total) * 100).toFixed(3)) 
                : 0;
              
              setFundDetailProgress({
                total: total,
                downloaded: currentIndex,
                percentage: percentage,
                status: 'downloading'
              });
              
              // 开始轮询获取进度
              startProgressPolling();
            } else {
              // 如果没有详细进度信息，但状态是下载中
              setFundDetailProgress(prev => ({
                ...prev,
                status: 'downloading'
              }));
              
              // 开始轮询获取进度
              startProgressPolling();
            }
          } else if (currentStatus === 'completed' || currentStatus === 'COMPLETED') {
            // 如果已完成，更新状态
            if (progressInfo && progressInfo.progress) {
              const progressData = progressInfo.progress;
              const successCount = progressData.success_count || 0;
              
              setFundDetailProgress({
                total: progressData.total_count || 0,
                downloaded: progressData.current_index || 0,
                percentage: 100,
                status: 'completed'
              });
            }
          } else if (currentStatus === 'error' || currentStatus === 'ERROR') {
            // 如果有错误，更新状态
            setFundDetailProgress(prev => ({
              ...prev,
              status: 'error'
            }));
          }
        }
        
        // 检查基金列表下载状态
        const listProgressResponse = await dataAPI.getDownloadProgress();
        if (listProgressResponse.status === 'success' && listProgressResponse.data) {
          const data = listProgressResponse.data;
          const fundListData = data.fund_list;
          
          if (fundListData && fundListData.status === 'downloading') {
            setFundListProgress({
              total: fundListData.total || 0,
              downloaded: fundListData.downloaded || 0,
              status: 'downloading'
            });
            // 可以在这里添加基金列表的轮询逻辑
          } else if (fundListData && fundListData.status === 'completed') {
            setFundListProgress({
              total: fundListData.total || 0,
              downloaded: fundListData.downloaded || 0,
              status: 'completed'
            });
          }
        }
        
      // 获取已入库基金统计
        const countResponse = await dataAPI.getStoredFundCount();
        if (countResponse.status === 'success') {
          setStoredFundCount(countResponse.data.total_funds_in_detail);
          setTotalFundCount(countResponse.data.total_funds_in_info);
        }

        // 检查基金净值下载状态
        const navStatusResponse = await dataAPI.getFundNavDownloadStatus();
        if (navStatusResponse.success === true) {
          const navData = navStatusResponse.data;
          if (navData.status === 'downloading') {
            setFundNavProgress({
              total: navData.total_funds || 0,
              downloaded: navData.downloaded_funds || 0,
              percentage: navData.total_funds > 0 ? parseFloat(((navData.downloaded_funds / navData.total_funds) * 100).toFixed(3)) : 0,
              status: 'downloading'
            });
            startNavProgressPolling();
          } else if (navData.status === 'completed') {
            setFundNavProgress({
              total: navData.total_funds || 0,
              downloaded: navData.downloaded_funds || 0,
              percentage: 100,
              status: 'completed'
            });
          } else if (navData.status === 'stopped') {
            setFundNavProgress({
              total: navData.total_funds || 0,
              downloaded: navData.downloaded_funds || 0,
              percentage: navData.total_funds > 0 ? parseFloat(((navData.downloaded_funds / navData.total_funds) * 100).toFixed(3)) : 0,
              status: 'stopped'
            });
          }
        }

        // 获取基金净值下载统计
        const navStatsResponse = await dataAPI.getFundNavDownloadStatistics();
        if (navStatsResponse.success === true) {
          setNavStatistics(navStatsResponse.data);
        }
        
      } catch (error) {
        console.error('检查后端状态失败:', error);
        // 静默失败，不显示错误消息
      }
    };

  // 组件挂载时检查后端状态
  useEffect(() => {
    // 页面加载时检查状态
    checkBackendStatus();
    
    // 建立WebSocket连接以实现实时状态同步
    setupWebSocketConnections();
    
    // 清理函数
    return () => {
      if (pollTimeoutId) {
        clearTimeout(pollTimeoutId);
      }
      // 断开所有WebSocket连接
      websocketService.disconnectAll();
    };
  }, []);

  // 设置WebSocket连接以实现状态同步
  const setupWebSocketConnections = () => {
    // 基金详细信息下载进度WebSocket
    websocketService.connect('fund-detail', {
      onMessage: (data) => {
        if (data.type === 'progress') {
          const progressData = data.progress;
          const total = progressData.total_count || 0;
          const currentIndex = progressData.current_index || 0;
          const percentage = total > 0 ? parseFloat(((currentIndex / total) * 100).toFixed(3)) : 0;
          
          setFundDetailProgress({
            total: total,
            downloaded: currentIndex,
            percentage: percentage,
            status: 'downloading'
          });
          
          setConnectionStatus('connected');
          setLastUpdateTime(new Date());
        } else if (data.type === 'completed') {
          const successCount = data.progress?.success_count || 0;
          message.success(`下载完成！共下载 ${successCount} 条基金详细信息`);
          setFundDetailProgress(prev => ({ ...prev, status: 'completed' }));
          setFundDetailTaskId(null);
          setIsPolling(false);
          setConnectionStatus('disconnected');
          
          // 更新统计信息
          updateStatistics();
        } else if (data.type === 'error') {
          message.error('下载过程中出现错误');
          setFundDetailProgress(prev => ({ ...prev, status: 'error' }));
          setFundDetailTaskId(null);
          setIsPolling(false);
          setConnectionStatus('disconnected');
        }
      },
      onError: (error) => {
        console.error('基金详细信息WebSocket错误:', error);
        // WebSocket错误时回退到HTTP轮询
        if (fundDetailTaskId) {
          startProgressPolling();
        }
      }
    });

    // 基金净值下载进度WebSocket
    websocketService.connect('fund-nav', {
      onMessage: (data) => {
        if (data.type === 'progress') {
          const progressData = data.progress;
          const total = progressData.total_count || 0;
          const downloaded = progressData.current_index || 0;
          const percentage = total > 0 ? parseFloat(((downloaded / total) * 100).toFixed(3)) : 0;
          
          setFundNavProgress({
            total: total,
            downloaded: downloaded,
            percentage: percentage,
            status: 'downloading'
          });
          
          setConnectionStatus('connected');
          setLastUpdateTime(new Date());
        } else if (data.type === 'completed') {
          const successCount = data.progress?.success_count || 0;
          message.success(`基金净值下载完成！共下载 ${successCount} 条记录`);
          setFundNavProgress(prev => ({ ...prev, status: 'completed', percentage: 100 }));
          setFundNavTaskId(null);
          setIsPolling(false);
          setConnectionStatus('disconnected');
          
          // 更新统计信息
          updateStatistics();
        } else if (data.type === 'error') {
          message.error('基金净值下载过程中出现错误');
          setFundNavProgress(prev => ({ ...prev, status: 'error' }));
          setFundNavTaskId(null);
          setIsPolling(false);
          setConnectionStatus('disconnected');
        }
      },
      onError: (error) => {
        console.error('基金净值WebSocket错误:', error);
        // WebSocket错误时回退到HTTP轮询
        if (fundNavTaskId) {
          startNavProgressPolling();
        }
      }
    });

    // 基金列表下载进度WebSocket
    websocketService.connect('fund-list', {
      onMessage: (data) => {
        if (data.type === 'progress') {
          const progressData = data.progress;
          const total = progressData.total_count || 0;
          const downloaded = progressData.current_index || 0;
          const percentage = total > 0 ? parseFloat(((downloaded / total) * 100).toFixed(3)) : 0;
          
          setFundListProgress({
            total: total,
            downloaded: downloaded,
            percentage: percentage,
            status: 'downloading'
          });
          
          setConnectionStatus('connected');
          setLastUpdateTime(new Date());
        } else if (data.type === 'completed') {
          const successCount = data.progress?.success_count || 0;
          message.success(`基金列表下载完成！共下载 ${successCount} 条记录`);
          setFundListProgress(prev => ({ ...prev, status: 'completed', percentage: 100 }));
          setFundListTaskId(null);
          setIsPolling(false);
          setConnectionStatus('disconnected');
          
          // 更新统计信息
          updateStatistics();
        } else if (data.type === 'error') {
          message.error('基金列表下载过程中出现错误');
          setFundListProgress(prev => ({ ...prev, status: 'error' }));
          setFundListTaskId(null);
          setIsPolling(false);
          setConnectionStatus('disconnected');
        }
      },
      onError: (error) => {
        console.error('基金列表WebSocket错误:', error);
        // WebSocket错误时回退到HTTP轮询
        if (fundListTaskId) {
          // 基金列表下载通常不需要单独轮询，使用基本信息刷新
          checkBackendStatus();
        }
      }
    });
  };

  // 更新统计信息的辅助函数
  const updateStatistics = async () => {
    try {
      // 更新基金详细信息统计
      const statsResponse = await dataAPI.getStoredFundCount();
      if (statsResponse.status === 'success') {
        setStoredFundCount(statsResponse.data.total_funds_in_detail);
        setTotalFundCount(statsResponse.data.total_funds_in_info);
      }
      
      // 更新基金净值下载统计
      const navStatsResponse = await dataAPI.getFundNavDownloadStatistics();
      if (navStatsResponse.success === true) {
        setNavStatistics(navStatsResponse.data);
      }
    } catch (error) {
      console.warn('更新统计信息失败:', error);
    }
  };

  // 开始轮询进度的通用函数
  const startProgressPolling = () => {
    let retryCount = 0;
    const maxRetries = 10;
    let pollInterval = 1000; // 初始轮询间隔1秒
    let lastProgressTime = Date.now();
    let consecutiveNoChange = 0;
    
    setIsPolling(true);
    setConnectionStatus('connecting');
    
    const pollProgress = async () => {
      try {
        setConnectionStatus('connecting');
        const progressResponse = await dataAPI.getFundDownloadStatus();
        
        // 更新连接状态和最后更新时间
        setConnectionStatus('connected');
        setLastUpdateTime(new Date());
        
        if (progressResponse.success === true) {
          const responseData = progressResponse.data;
          const currentStatus = responseData.current_status;
          const progressInfo = responseData.progress;
          
          if (progressInfo && progressInfo.progress) {
            // 重置重试计数
            retryCount = 0;
            
            const progressData = progressInfo.progress;
            const total = progressData.total_count || 0;
            const currentIndex = progressData.current_index || 0;
            const percentage = total > 0 
              ? parseFloat(((currentIndex / total) * 100).toFixed(3)) 
              : 0;
            
            // 检查进度是否有变化
            const currentProgress = currentIndex;
            const prevProgress = fundDetailProgress.downloaded;
            
            if (currentProgress > prevProgress) {
              // 有进度变化，重置计数器，使用较快的轮询频率
              consecutiveNoChange = 0;
              pollInterval = 1000;
              lastProgressTime = Date.now();
            } else {
              // 无进度变化，增加计数器
              consecutiveNoChange++;
              // 根据无变化次数调整轮询频率
              if (consecutiveNoChange > 3) {
                pollInterval = Math.min(5000, 1000 + consecutiveNoChange * 500);
              }
            }
            
            setFundDetailProgress({
              total: total,
              downloaded: currentIndex,
              percentage: percentage,
              status: currentStatus === 'completed' || currentStatus === 'COMPLETED' ? 'completed' : 
                      currentStatus === 'error' || currentStatus === 'ERROR' ? 'error' : 'downloading'
            });
            
            // 自动更新统计信息（每10次轮询或有进度变化时）
            if (consecutiveNoChange === 0 || consecutiveNoChange % 10 === 0) {
              try {
                const statsResponse = await dataAPI.getStoredFundCount();
                if (statsResponse.status === 'success') {
                  setStoredFundCount(statsResponse.data.total_funds_in_detail);
                  setTotalFundCount(statsResponse.data.total_funds_in_info);
                }
              } catch (error) {
                // 静默处理统计更新错误
                console.warn('更新统计信息失败:', error);
              }
            }
          } else {
            // 如果没有progress数据，使用基本的状态信息
            setFundDetailProgress(prev => ({
              ...prev,
              status: currentStatus === 'completed' || currentStatus === 'COMPLETED' ? 'completed' : 
                      currentStatus === 'error' || currentStatus === 'ERROR' ? 'error' : 'downloading'
            }));
          }
      
          if (currentStatus === 'completed' || currentStatus === 'COMPLETED') {
            const successCount = progressInfo?.progress?.success_count || 0;
            message.success(`下载完成！共下载 ${successCount} 条基金详细信息`);
            setFundDetailTaskId(null);
            setIsPolling(false);
            setConnectionStatus('disconnected');
            // 最终更新统计信息
              try {
                // 更新基金详细信息统计
                const statsResponse = await dataAPI.getStoredFundCount();
                if (statsResponse.status === 'success') {
                  setStoredFundCount(statsResponse.data.total_funds_in_detail);
                  setTotalFundCount(statsResponse.data.total_funds_in_info);
                }
                
                // 更新基金净值下载统计
                const navStatsResponse = await dataAPI.getFundNavDownloadStatistics();
                if (navStatsResponse.success === true) {
                  setNavStatistics(navStatsResponse.data);
                }
              } catch (error) {
                console.warn('最终统计更新失败:', error);
              }
            return;
          } else if (currentStatus === 'error' || currentStatus === 'ERROR') {
            setFundDetailProgress(prev => ({ ...prev, status: 'error' }));
            message.error('下载过程中出现错误');
            setFundDetailTaskId(null);
            setIsPolling(false);
            setConnectionStatus('disconnected');
            return;
          }
      
          // 使用动态轮询间隔继续轮询
          const timeoutId = setTimeout(pollProgress, pollInterval);
          setPollTimeoutId(timeoutId);
        } else {
          retryCount++;
          setConnectionStatus('disconnected');
          if (retryCount < maxRetries) {
            // 失败时使用较长的重试间隔
            const timeoutId = setTimeout(pollProgress, 3000);
            setPollTimeoutId(timeoutId);
          } else {
            message.error('获取下载进度失败，请手动刷新查看状态');
            setFundDetailProgress(prev => ({ ...prev, status: 'error' }));
            setFundDetailTaskId(null);
            setIsPolling(false);
            setConnectionStatus('disconnected');
          }
        }
      } catch (error: any) {
        console.error('轮询进度失败:', error);
        setConnectionStatus('disconnected');
        
        // 根据错误类型提供更详细的错误信息
        let errorMessage = '获取下载进度失败';
        if (error.code === 'NETWORK_ERROR' || error.message?.includes('Network Error')) {
          errorMessage = '网络连接失败，请检查网络状态';
        } else if (error.code === 'TIMEOUT' || error.message?.includes('timeout')) {
          errorMessage = '请求超时，请稍后重试';
        } else if (error.response?.status === 500) {
          errorMessage = '服务器内部错误，请稍后重试';
        } else if (error.response?.status === 404) {
          errorMessage = '下载任务不存在或已完成';
        }
        
        retryCount++;
        if (retryCount < maxRetries) {
          // 根据错误类型调整重试间隔
          const retryDelay = error.code === 'NETWORK_ERROR' ? 5000 : 3000;
          const timeoutId = setTimeout(pollProgress, retryDelay);
          setPollTimeoutId(timeoutId);
        } else {
          message.error(errorMessage);
          setFundDetailProgress(prev => ({ ...prev, status: 'error' }));
          setFundDetailTaskId(null);
          setIsPolling(false);
          setConnectionStatus('disconnected');
        }
      }
    };
    
    // 开始轮询
    const timeoutId = setTimeout(pollProgress, 1000);
    setPollTimeoutId(timeoutId);
  };

  // 开始轮询基金净值下载进度
  const startNavProgressPolling = () => {
    let retryCount = 0;
    const maxRetries = 10;
    let pollCount = 0;
    let lastDownloaded = 0;
    let pollingInterval = 1000; // 初始轮询间隔1秒
    
    const pollNavProgress = async () => {
      try {
        setIsPolling(true);
        setConnectionStatus('connecting');
        
        const progressResponse = await dataAPI.getFundNavDownloadStatus();
        
        if (progressResponse.success === true) {
          const navData = progressResponse.data;
          setConnectionStatus('connected');
          setLastUpdateTime(new Date());
          
          if (navData.status === 'downloading') {
            const total = navData.progress?.total_count || 0;
            const downloaded = navData.progress?.current_index || 0;
            const percentage = total > 0 ? parseFloat(((downloaded / total) * 100).toFixed(3)) : 0;
            
            // 检查进度是否有变化
            const progressChanged = downloaded !== lastDownloaded;
            if (progressChanged) {
              lastDownloaded = downloaded;
              pollingInterval = 1000; // 有进度变化时重置为1秒
            } else {
              // 无变化时逐步增加间隔，最大5秒
              pollingInterval = Math.min(pollingInterval + 500, 5000);
            }
            
            setFundNavProgress({
              total: total,
              downloaded: downloaded,
              percentage: percentage,
              status: 'downloading'
            });
            
            // 每10次轮询或进度变化时更新统计信息
              pollCount++;
              if (pollCount % 10 === 0 || progressChanged) {
                try {
                  // 更新基金详细信息统计
                  const statsResponse = await dataAPI.getStoredFundCount();
                  if (statsResponse.status === 'success') {
                    setStoredFundCount(statsResponse.data.total_funds_in_detail);
                    setTotalFundCount(statsResponse.data.total_funds_in_info);
                  }
                  
                  // 更新基金净值下载统计
                  const navStatsResponse = await dataAPI.getFundNavDownloadStatistics();
                  if (navStatsResponse.success === true) {
                    setNavStatistics(navStatsResponse.data);
                  }
                } catch (error) {
                  console.warn('更新统计信息失败:', error);
                }
              }
            
            // 继续轮询
            const timeoutId = setTimeout(pollNavProgress, pollingInterval);
            setNavPollTimeoutId(timeoutId);
          } else if (navData.status === 'completed') {
            // 下载完成
            const total = navData.progress?.total_count || 0;
            const downloaded = navData.progress?.success_count || navData.progress?.current_index || 0;
            setFundNavProgress({
              total: total,
              downloaded: downloaded,
              percentage: 100,
              status: 'completed'
            });
            
            // 最终更新统计信息
             try {
               // 更新基金详细信息统计
               const statsResponse = await dataAPI.getStoredFundCount();
               if (statsResponse.status === 'success') {
                 setStoredFundCount(statsResponse.data.total_funds_in_detail);
                 setTotalFundCount(statsResponse.data.total_funds_in_info);
               }
               
               // 更新基金净值下载统计
               const navStatsResponse = await dataAPI.getFundNavDownloadStatistics();
               if (navStatsResponse.success === true) {
                 setNavStatistics(navStatsResponse.data);
               }
             } catch (error) {
               console.warn('最终统计更新失败:', error);
             }
            
            message.success(`基金净值下载完成！共下载 ${downloaded} 只基金的净值数据`);
            setFundNavTaskId(null);
            setIsPolling(false);
            setConnectionStatus('disconnected');
          } else if (navData.status === 'error') {
            // 下载出错
            setFundNavProgress(prev => ({ ...prev, status: 'error' }));
            message.error('基金净值下载过程中出现错误');
            setFundNavTaskId(null);
            setIsPolling(false);
            setConnectionStatus('disconnected');
          } else {
            // 继续轮询
            const timeoutId = setTimeout(pollNavProgress, pollingInterval);
            setNavPollTimeoutId(timeoutId);
          }
        } else {
          setConnectionStatus('disconnected');
          retryCount++;
          if (retryCount < maxRetries) {
            // 失败时使用较长的重试间隔
            const timeoutId = setTimeout(pollNavProgress, 3000);
            setNavPollTimeoutId(timeoutId);
          } else {
            message.error('获取基金净值下载进度失败，请手动刷新查看状态');
            setFundNavProgress(prev => ({ ...prev, status: 'error' }));
            setFundNavTaskId(null);
            setIsPolling(false);
            setConnectionStatus('disconnected');
          }
        }
      } catch (error: any) {
        console.error('轮询基金净值下载进度失败:', error);
        
        // 根据错误类型提供更详细的错误信息
        let errorMessage = '获取基金净值下载进度失败';
        if (error.code === 'NETWORK_ERROR' || error.message?.includes('Network Error')) {
          errorMessage = '网络连接失败，请检查网络状态';
        } else if (error.code === 'TIMEOUT' || error.message?.includes('timeout')) {
          errorMessage = '请求超时，请稍后重试';
        } else if (error.response?.status === 500) {
          errorMessage = '服务器内部错误，请稍后重试';
        } else if (error.response?.status === 404) {
          errorMessage = '下载任务不存在或已完成';
        }
        
        retryCount++;
        if (retryCount < maxRetries) {
          // 根据错误类型调整重试间隔
          const retryDelay = error.code === 'NETWORK_ERROR' ? 5000 : 3000;
          const timeoutId = setTimeout(pollNavProgress, retryDelay);
          setNavPollTimeoutId(timeoutId);
        } else {
          message.error(errorMessage);
          setFundNavProgress(prev => ({ ...prev, status: 'error' }));
          setFundNavTaskId(null);
        }
      }
    };
    
    // 开始轮询
    const timeoutId = setTimeout(pollNavProgress, 1000);
    setNavPollTimeoutId(timeoutId);
  };

  // 检查数据库中是否有数据
  const checkDataExists = async (dataType: 'fund_list' | 'fund_detail'): Promise<boolean> => {
    try {
      const response = await dataAPI.checkDatabaseData();
      if (response.status === 'success') {
        const data = response.data;
        if (dataType === 'fund_list') {
          return data.fund_list?.has_data || false;
        } else if (dataType === 'fund_detail') {
          return data.fund_details?.has_data || false;
        }
      }
      return false;
    } catch (error) {
      console.error('检查数据库数据失败:', error);
      return false;
    }
  };

  // 显示确认删除对话框
  const showDeleteConfirm = (onConfirm: () => void) => {
    confirm({
      title: '数据库中存在数据',
      content: '数据库中存在数据，是否删除重新下载？',
      icon: <ExclamationCircleOutlined />,
      okText: '是',
      cancelText: '否',
      onOk: onConfirm,
      onCancel: () => {
        message.info('已取消下载');
      },
    });
  };

  // 获取已入库基金统计
  const handleGetStoredFundCount = async () => {
    try {
      const response = await dataAPI.getStoredFundCount();
      if (response.status === 'success') {
        setStoredFundCount(response.data.total_funds_in_detail);
        setTotalFundCount(response.data.total_funds_in_info);
        message.success(`已入库基金：${response.data.total_funds_in_detail} 条，总基金数：${response.data.total_funds_in_info} 条`);
      } else {
        message.error(response.message || '获取统计信息失败');
      }
    } catch (error: any) {
      console.error('获取已入库基金统计失败:', error);
      message.error('获取统计信息失败');
    }
  };

  // 继续下载基金详细信息
  const handleContinueDownload = async () => {
    try {
      // 先设置为下载状态，但保持之前的进度数据，避免显示0/0
      setFundDetailProgress(prev => ({ ...prev, status: 'downloading' }));
      
      const response = await dataAPI.continueFundDetailDownload();
      if (response.status === 'success') {
        // 保存任务ID
        if (response.data?.task_id) {
          setFundDetailTaskId(response.data.task_id.toString());
        }
        message.info('继续下载任务已启动，正在后台处理...');
        
        // 使用通用轮询函数
        startProgressPolling();
        
      } else {
        message.error(response.message || '启动继续下载失败');
        setFundDetailProgress(prev => ({ ...prev, status: 'error' }));
      }
    } catch (error: any) {
      console.error('继续下载基金详细信息失败:', error);
      message.error('启动继续下载失败');
      setFundDetailProgress(prev => ({ ...prev, status: 'error' }));
    }
  };

  // 开始基金净值下载（重置后重新下载）
  const handleStartFundNavDownload = async () => {
    try {
      setFundNavProgress(prev => ({ ...prev, status: 'downloading' }));
      
      // 先重置下载状态
      const resetResponse = await dataAPI.resetFundNavDownload();
      if (resetResponse.success !== true) {
        message.error(resetResponse.message || '重置下载状态失败');
        setFundNavProgress(prev => ({ ...prev, status: 'error' }));
        return;
      }
      
      // 然后启动新的下载任务
      const response = await dataAPI.startFundNavDownload();
      if (response.success === true) {
        message.info('基金净值下载任务已重置并启动，正在下载所有基金净值数据...');
        startNavProgressPolling();
      } else {
        message.error(response.message || '启动基金净值下载失败');
        setFundNavProgress(prev => ({ ...prev, status: 'error' }));
      }
    } catch (error: any) {
      console.error('启动基金净值下载失败:', error);
      message.error('启动基金净值下载失败');
      setFundNavProgress(prev => ({ ...prev, status: 'error' }));
    }
  };

  // 继续基金净值下载
  const handleContinueFundNavDownload = async () => {
    try {
      setFundNavProgress(prev => ({ ...prev, status: 'downloading' }));
      
      const response = await dataAPI.continueFundNavDownload();
      if (response.success === true) {
        message.info('继续基金净值下载任务已启动，正在后台处理...');
        startNavProgressPolling();
      } else {
        message.error(response.message || '启动继续基金净值下载失败');
        setFundNavProgress(prev => ({ ...prev, status: 'error' }));
      }
    } catch (error: any) {
      console.error('继续基金净值下载失败:', error);
      message.error('启动继续基金净值下载失败');
      setFundNavProgress(prev => ({ ...prev, status: 'error' }));
    }
  };

  // 获取基金净值下载统计
  const handleGetNavStatistics = async () => {
    try {
      const response = await dataAPI.getFundNavDownloadStatistics();
      if (response.success === true) {
        setNavStatistics(response.data);
        message.success('统计信息已更新');
      } else {
        message.error(response.message || '获取统计信息失败');
      }
    } catch (error: any) {
      console.error('获取基金净值下载统计失败:', error);
      message.error('获取统计信息失败');
    }
  };

  // 基金列表下载
  const handleDownloadFundList = async () => {
    try {
      // 检查数据是否存在
      const dataExists = await checkDataExists('fund_list');
      
      const doDownload = async () => {
        // 先设置为下载状态，但保持之前的进度数据，避免显示0/0
        setFundListProgress(prev => ({ ...prev, status: 'downloading' }));
        
        try {
          // 启动下载任务
          const response = await dataAPI.downloadFundList({ fund_type: 'all' });
          
          if (response.data?.success || response.success) {
            message.info('基金列表下载任务已启动，正在后台处理...');
            
            // 轮询获取下载进度
            let retryCount = 0;
            const maxRetries = 10;
            
            const pollProgress = async () => {
              try {
                const progressResponse = await dataAPI.getDownloadProgress();
                
                if (progressResponse.success === true && progressResponse.data) {
                  const data = progressResponse.data;
                  const fundListData = data.fund_list;
                  
                  if (fundListData) {
                    setFundListProgress({
                      total: fundListData.total || 0,
                      downloaded: fundListData.downloaded || 0,
                      status: fundListData.status === 'completed' ? 'completed' : 'downloading'
                    });
                    
                    if (fundListData.status === 'completed') {
                      message.success(`基金列表下载完成！共下载 ${fundListData.downloaded} 条基金信息`);
                      return;
                    } else if (fundListData.status === 'error') {
                      setFundListProgress(prev => ({ ...prev, status: 'error' }));
                      message.error('下载过程中出现错误');
                      return;
                    }
                  }
                  
                  // 继续轮询
                  setTimeout(pollProgress, 2000);
                } else {
                  retryCount++;
                  if (retryCount < maxRetries) {
                    setTimeout(pollProgress, 3000);
                  } else {
                    message.error('获取下载进度失败，请手动刷新查看状态');
                    setFundListProgress(prev => ({ ...prev, status: 'error' }));
                  }
                }
              } catch (error: any) {
                 console.error('轮询进度失败:', error);
                 
                 // 根据错误类型提供更详细的错误信息
                 let errorMessage = '获取下载进度失败';
                 if (error.code === 'NETWORK_ERROR' || error.message?.includes('Network Error')) {
                   errorMessage = '网络连接失败，请检查网络状态';
                 } else if (error.code === 'TIMEOUT' || error.message?.includes('timeout')) {
                   errorMessage = '请求超时，请稍后重试';
                 } else if (error.response?.status === 500) {
                   errorMessage = '服务器内部错误，请稍后重试';
                 }
                 
                 retryCount++;
                 if (retryCount < maxRetries) {
                   // 根据错误类型调整重试间隔
                   const retryDelay = error.code === 'NETWORK_ERROR' ? 5000 : 3000;
                   setTimeout(pollProgress, retryDelay);
                 } else {
                   message.error(errorMessage);
                   setFundListProgress(prev => ({ ...prev, status: 'error' }));
                 }
               }
            };
            
            // 开始轮询
            setTimeout(pollProgress, 1000);
            
          } else {
            message.error(response.message || '启动下载失败');
            setFundListProgress(prev => ({ ...prev, status: 'error' }));
          }
        } catch (error: any) {
          console.error('下载基金列表失败:', error);
          message.error('下载基金列表失败');
          setFundListProgress(prev => ({ ...prev, status: 'error' }));
        }
      };
      
      if (dataExists) {
        showDeleteConfirm(doDownload);
      } else {
        await doDownload();
      }
    } catch (error: any) {
      console.error('下载基金列表失败:', error);
      message.error('下载基金列表失败');
    }
  };

  // 基金详细信息下载
  const handleDownloadFundDetail = async () => {
    try {
      // 检查数据是否存在
      const dataExists = await checkDataExists('fund_detail');
      
      const doDownload = async () => {
        // 先设置为下载状态，但保持之前的进度数据，避免显示0/0
        setFundDetailProgress(prev => ({ ...prev, status: 'downloading' }));
        
        try {
          // 启动下载任务
          const response = await dataAPI.updateFundDetail();
          
          if (response.status === 'success') {
            // 保存任务ID
            if (response.data?.task_id) {
              setFundDetailTaskId(response.data.task_id.toString());
            }
            message.info('基金详细信息下载任务已启动，正在后台处理...');
            
            // 使用通用轮询函数
            startProgressPolling();
            
          } else {
            message.error(response.message || '启动下载失败');
            setFundDetailProgress(prev => ({ ...prev, status: 'error' }));
          }
        } catch (error: any) {
          console.error('下载基金详细信息失败:', error);
          message.error('下载基金详细信息失败');
          setFundDetailProgress(prev => ({ ...prev, status: 'error' }));
        }
      };
      
      if (dataExists) {
        showDeleteConfirm(doDownload);
      } else {
        await doDownload();
      }
    } catch (error: any) {
      console.error('下载基金详细信息失败:', error);
      message.error('下载基金详细信息失败');
    }
  };



  // 状态指示器组件
  const StatusIndicator = () => {
    const getStatusIcon = () => {
      switch (connectionStatus) {
        case 'connected':
          return <WifiOutlined style={{ color: '#52c41a' }} />;
        case 'connecting':
          return <LoadingOutlined style={{ color: '#1890ff' }} />;
        case 'disconnected':
        default:
          return <DisconnectOutlined style={{ color: '#ff4d4f' }} />;
      }
    };

    const getStatusText = () => {
      switch (connectionStatus) {
        case 'connected':
          return '已连接';
        case 'connecting':
          return '连接中';
        case 'disconnected':
        default:
          return '未连接';
      }
    };

    const getStatusColor = () => {
      switch (connectionStatus) {
        case 'connected':
          return 'success';
        case 'connecting':
          return 'processing';
        case 'disconnected':
        default:
          return 'error';
      }
    };

    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
        <Tooltip title={`状态: ${getStatusText()}${lastUpdateTime ? ` | 最后更新: ${lastUpdateTime.toLocaleTimeString()}` : ''}`}>
          <Badge status={getStatusColor()} text={
            <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
              {getStatusIcon()}
              <Text type="secondary" style={{ fontSize: '12px' }}>
                {getStatusText()}
                {isPolling && ' (轮询中)'}
              </Text>
            </span>
          } />
        </Tooltip>
        {lastUpdateTime && (
          <Text type="secondary" style={{ fontSize: '12px' }}>
            最后更新: {lastUpdateTime.toLocaleTimeString()}
          </Text>
        )}
      </div>
    );
  };

  return (
    <MainLayout>
      <div>
        <div style={{ marginBottom: 24 }}>
          <Title level={2}>基金信息下载</Title>
          <Text type="secondary">下载和管理基金数据信息</Text>
        </div>

        {/* 状态概览 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={6}>
            <Card>
              <Statistic
                title="基金总数"
                value={totalFundCount}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={6}>
            <Card>
              <Statistic
                title="已存储基金"
                value={storedFundCount}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={6}>
            <Card>
              <Statistic
                title="连接状态"
                value={connectionStatus === 'connected' ? '已连接' : connectionStatus === 'connecting' ? '连接中' : '未连接'}
                valueStyle={{ 
                  color: connectionStatus === 'connected' ? '#52c41a' : 
                         connectionStatus === 'connecting' ? '#1890ff' : '#ff4d4f'
                }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={6}>
            <Card>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div>
                  <div style={{ fontSize: '14px', color: '#666', marginBottom: '4px' }}>系统状态</div>
                  <StatusIndicator />
                </div>
              </div>
            </Card>
          </Col>
        </Row>
      
      <Space direction="vertical" size="large" style={{ width: '100%' }}>
        {/* 基金列表下载 */}
        <Card 
          title="基金列表下载" 
          style={{ width: '100%' }}
          extra={
            <Button 
              type="primary" 
              icon={<DownloadOutlined />} 
              loading={fundListProgress.status === 'downloading'}
              onClick={handleDownloadFundList}
            >
              下载
            </Button>
          }
        >
          <Space direction="vertical" style={{ width: '100%' }}>
            {fundListProgress.status === 'downloading' && (
              <div>
                <div style={{ marginBottom: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text>正在下载基金列表...</Text>
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    {fundListProgress.total > 0 
                      ? `${parseFloat(((fundListProgress.downloaded / fundListProgress.total) * 100).toFixed(2))}% (${fundListProgress.downloaded.toLocaleString()}/${fundListProgress.total.toLocaleString()})`
                      : '正在初始化...'
                    }
                  </Text>
                </div>
                {fundListProgress.total > 0 ? (
                  <Progress 
                    percent={parseFloat(((fundListProgress.downloaded / fundListProgress.total) * 100).toFixed(3))} 
                    status="active"
                    strokeColor={{
                      '0%': '#108ee9',
                      '100%': '#87d068',
                    }}
                    format={(percent) => {
                      if (percent === undefined) return '0%';
                      return `${percent.toFixed(1)}%`;
                    }}
                  />
                ) : (
                  <Progress 
                    percent={0} 
                    status="active"
                    format={() => '正在初始化...'}
                  />
                )}
                <div style={{ marginTop: 4, fontSize: '12px', color: '#666' }}>
                  <Text type="secondary">
                    {fundListProgress.total > 0 && (
                      `预计剩余: ${Math.max(0, fundListProgress.total - fundListProgress.downloaded).toLocaleString()} 条`
                    )}
                  </Text>
                </div>
              </div>
            )}
            
            {fundListProgress.status === 'completed' && (
              <Text type="success">✓ 下载完成，共 {fundListProgress.downloaded} 条基金信息</Text>
            )}
            
            {fundListProgress.status === 'error' && (
              <div>
                <Text type="danger">✗ 下载失败</Text>
                <Progress 
                  percent={fundListProgress.total > 0 ? parseFloat(((fundListProgress.downloaded / fundListProgress.total) * 100).toFixed(3)) : 0} 
                  status="exception" 
                />
              </div>
            )}
            
            {fundListProgress.status === 'idle' && (
              <Text type="secondary">点击下载按钮开始下载基金列表</Text>
            )}
          </Space>
        </Card>
        
        {/* 基金详细信息下载 */}
        <Card 
          title="基金详细信息下载" 
          style={{ width: '100%' }}
          extra={
            <Space>
              <Button 
                type="primary" 
                icon={<DownloadOutlined />} 
                loading={fundDetailProgress.status === 'downloading'}
                onClick={handleDownloadFundDetail}
              >
                下载
              </Button>
              <Button 
                icon={<BarChartOutlined />} 
                onClick={handleGetStoredFundCount}
                disabled={fundDetailProgress.status === 'downloading'}
              >
                统计
              </Button>
              <Button 
                icon={<PlayCircleOutlined />} 
                onClick={handleContinueDownload}
                disabled={fundDetailProgress.status === 'downloading'}
              >
                继续下载
              </Button>
              {fundDetailProgress.status === 'downloading' && (
                <Button 
                  onClick={async () => {
                    // 清除轮询定时器
                    if (pollTimeoutId) {
                      clearTimeout(pollTimeoutId);
                      setPollTimeoutId(null);
                    }
                    
                    if (fundDetailTaskId) {
                      try {
                        await dataAPI.stopFundDownload();
                        message.success('已发送停止指令');
                      } catch (error) {
                        console.error('停止下载失败:', error);
                        message.error('停止下载失败');
                      }
                    }
                    
                    // 立即设置状态为idle
                    setFundDetailProgress({ total: 0, downloaded: 0, percentage: 0, status: 'idle' });
                    setFundDetailTaskId(null);
                    setCurrentTaskId(null);
                  }}
                >
                  停止
                </Button>
              )}
            </Space>
          }
        >
          <Space direction="vertical" style={{ width: '100%' }}>
            {/* 统计信息显示 */}
            {(storedFundCount > 0 || totalFundCount > 0) && (
              <div style={{ marginBottom: 16 }}>
                <Space size="large">
                  <Statistic 
                    title="已入库基金" 
                    value={storedFundCount} 
                    suffix="条"
                    valueStyle={{ color: '#3f8600' }}
                  />
                  <Statistic 
                    title="总基金数" 
                    value={totalFundCount} 
                    suffix="条"
                  />
                  {totalFundCount > 0 && (
                    <Statistic 
                      title="入库进度" 
                      value={((storedFundCount / totalFundCount) * 100).toFixed(1)} 
                      suffix="%"
                      valueStyle={{ color: storedFundCount === totalFundCount ? '#3f8600' : '#1890ff' }}
                    />
                  )}
                </Space>
                <Divider />
              </div>
            )}
            
            {fundDetailProgress.status === 'downloading' && (
              <div>
                <div style={{ marginBottom: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text>正在下载基金详细信息...</Text>
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    {fundDetailProgress.total > 0 
                      ? `${fundDetailProgress.percentage.toFixed(2)}% (${fundDetailProgress.downloaded.toLocaleString()}/${fundDetailProgress.total.toLocaleString()})`
                      : '正在初始化...'
                    }
                  </Text>
                </div>
                {fundDetailProgress.total > 0 ? (
                  <Progress 
                    percent={fundDetailProgress.percentage} 
                    status="active"
                    strokeColor={{
                      '0%': '#108ee9',
                      '100%': '#87d068',
                    }}
                    format={(percent) => {
                      if (percent === undefined) return '0%';
                      return `${percent.toFixed(1)}%`;
                    }}
                  />
                ) : (
                  <Progress 
                    percent={0} 
                    status="active"
                    format={() => '正在初始化...'}
                  />
                )}
                <div style={{ marginTop: 4, fontSize: '12px', color: '#666' }}>
                  <Text type="secondary">
                    {fundDetailProgress.total > 0 && (
                      `预计剩余: ${Math.max(0, fundDetailProgress.total - fundDetailProgress.downloaded).toLocaleString()} 条`
                    )}
                  </Text>
                </div>
              </div>
            )}
            
            {fundDetailProgress.status === 'completed' && (
              <Text type="success">✓ 下载完成，共 {fundDetailProgress.downloaded} 条详细信息</Text>
            )}
            
            {fundDetailProgress.status === 'error' && (
              <div>
                <Text type="danger">✗ 下载失败</Text>
                <Progress 
                  percent={fundDetailProgress.total > 0 ? parseFloat(((fundDetailProgress.downloaded / fundDetailProgress.total) * 100).toFixed(3)) : 0} 
                  status="exception" 
                />
              </div>
            )}
            
            {fundDetailProgress.status === 'idle' && (
              <Text type="secondary">点击下载按钮开始下载基金详细信息，支持进度显示</Text>
            )}
          </Space>
        </Card>

        {/* 基金净值下载 */}
        <Card 
          title="基金净值下载" 
          style={{ width: '100%' }}
          extra={
            <Space>
              <Button 
                type="primary" 
                icon={<DownloadOutlined />} 
                loading={fundNavProgress.status === 'downloading'}
                onClick={handleStartFundNavDownload}
                disabled={fundNavProgress.status === 'downloading'}
              >
                下载
              </Button>
              <Button 
                icon={<ReloadOutlined />} 
                onClick={async () => {
                  try {
                    // 清除轮询定时器
                    if (navPollTimeoutId) {
                      clearTimeout(navPollTimeoutId);
                      setNavPollTimeoutId(null);
                    }
                    
                    await dataAPI.restartFundNavDownload();
                    message.success('重新下载已开始');
                    
                    // 重置进度状态
                     setFundNavProgress({
                       total: 0,
                       downloaded: 0,
                       percentage: 0,
                       status: 'downloading'
                     });
                     
                     // 开始轮询状态
                     startNavProgressPolling();
                  } catch (error) {
                    console.error('重新下载失败:', error);
                    message.error('重新下载失败');
                  }
                }}
                disabled={fundNavProgress.status === 'downloading'}
              >
                重新下载
              </Button>
              <Button 
                icon={<BarChartOutlined />} 
                onClick={handleGetNavStatistics}
                disabled={fundNavProgress.status === 'downloading'}
              >
                统计
              </Button>
              <Button 
                icon={<PlayCircleOutlined />} 
                onClick={handleContinueFundNavDownload}
                disabled={fundNavProgress.status === 'downloading'}
                type={fundNavProgress.status === 'stopped' ? 'primary' : 'default'}
              >
                继续下载
              </Button>
              {fundNavProgress.status === 'downloading' && (
                <Button 
                  onClick={async () => {
                    // 清除轮询定时器
                    if (navPollTimeoutId) {
                      clearTimeout(navPollTimeoutId);
                      setNavPollTimeoutId(null);
                    }
                    
                    try {
                      await dataAPI.stopFundNavDownload();
                      message.success('已发送停止指令');
                      
                      // 设置状态为stopped，保留当前进度信息以支持继续下载
                      setFundNavProgress(prev => ({ 
                        ...prev, 
                        status: 'stopped' 
                      }));
                    } catch (error) {
                      console.error('停止基金净值下载失败:', error);
                      message.error('停止下载失败');
                    }
                  }}
                >
                  停止
                </Button>
              )}
            </Space>
          }
        >
          <Space direction="vertical" style={{ width: '100%' }}>
            {/* 统计信息显示 */}
            {navStatistics && (
              <div style={{ marginBottom: 16 }}>
                <Space size="large">
                  <Statistic 
                    title="待下载基金" 
                    value={navStatistics.pending_funds || 0} 
                    suffix="只"
                    valueStyle={{ color: '#1890ff' }}
                  />
                  <Statistic 
                    title="已下载基金" 
                    value={navStatistics.downloaded_funds || 0} 
                    suffix="只"
                    valueStyle={{ color: '#3f8600' }}
                  />
                  <Statistic 
                    title="总基金数" 
                    value={navStatistics.total_funds || 0} 
                    suffix="只"
                  />
                  {navStatistics.total_funds > 0 && (
                    <Statistic 
                      title="下载进度" 
                      value={((navStatistics.downloaded_funds / navStatistics.total_funds) * 100).toFixed(1)} 
                      suffix="%"
                      valueStyle={{ color: navStatistics.downloaded_funds === navStatistics.total_funds ? '#3f8600' : '#1890ff' }}
                    />
                  )}
                </Space>
                <Divider />
              </div>
            )}
            
            {fundNavProgress.status === 'downloading' && (
              <div>
                <Text>正在下载基金净值数据... ({fundNavProgress.percentage}%)</Text>
                {fundNavProgress.total > 0 ? (
                  <Progress 
                    percent={fundNavProgress.percentage} 
                    status="active"
                    format={() => `${fundNavProgress.downloaded}/${fundNavProgress.total}`}
                  />
                ) : (
                  <Progress 
                    percent={0} 
                    status="active"
                    format={() => '正在初始化...'}
                  />
                )}
              </div>
            )}
            
            {fundNavProgress.status === 'completed' && (
              <Text type="success">✓ 下载完成，共 {fundNavProgress.downloaded} 只基金的净值数据</Text>
            )}
            
            {fundNavProgress.status === 'error' && (
              <div>
                <Text type="danger">✗ 下载失败</Text>
                <Progress 
                  percent={fundNavProgress.total > 0 ? parseFloat(((fundNavProgress.downloaded / fundNavProgress.total) * 100).toFixed(3)) : 0} 
                  status="exception" 
                />
              </div>
            )}
            
            {fundNavProgress.status === 'stopped' && (
              <div>
                <Text type="warning">⏸ 下载已停止 ({fundNavProgress.percentage}%)</Text>
                {fundNavProgress.total > 0 ? (
                  <Progress 
                    percent={fundNavProgress.percentage} 
                    status="normal"
                    format={() => `${fundNavProgress.downloaded}/${fundNavProgress.total}`}
                  />
                ) : (
                  <Progress 
                    percent={0} 
                    status="normal"
                    format={() => '已停止'}
                  />
                )}
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  点击"继续下载"按钮可以从当前进度继续下载
                </Text>
              </div>
            )}
            
            {fundNavProgress.status === 'idle' && (
              <Text type="secondary">点击下载按钮开始下载基金净值数据，支持进度显示和断点续传</Text>
            )}
          </Space>
        </Card>


      </Space>
      </div>
    </MainLayout>
  );
};

export default FundDataDownloader;